package ts.test.test;

import java.lang.reflect.Method;

public class AccessPersonMethods {
    public static void main(String[] args) {
        try{
            //创建Person对象
            Class clz = Class.forName("ts.test.test.Parson");

            //没有参数可以不用写或者用NULL表示
            Method getAge = clz.getDeclaredMethod("getAge", null);
            //调用方法
            getAge.setAccessible(true);
            Object age = getAge.invoke(null, null);
            System.out.println("年龄是：" + age);

            Object person = clz.newInstance(); //创建对象
            Method silentMethod = clz.getDeclaredMethod("silentMethod", null);
            silentMethod.setAccessible(true);
            silentMethod.invoke(person, null);

            // 获取方法
            Method setName = clz.getDeclaredMethod("setName", String.class);
            //setName方法为public
            setName.invoke(person, "New Person");

            //验证一下结果，调用public
            Object returnName = clz.getDeclaredMethod("getName").invoke(person);
            System.out.println( "刚刚设定的name是："+returnName);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
